package com.zhou.hot.update;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Created by zhouyongjun on 2020/4/17
 */
public class HotUpdateConfig {
    public static final String FILE = "hot/hotupdate.properties";
    public String hotLoadAgentJar = "HotLoadAgent.jar";
    public String pidFile = "pid.RedAlert";
    public Logger logger = LoggerFactory.getLogger("hot.load");
    public boolean load() throws Exception {
        String path = this.getClass().getResource("/").getPath() +FILE;
        logger.info("hot update 启动.... load hot config ="+path);

        File file = new File(path);
        Properties properties = new Properties();
        FileInputStream in = null;
        try {
            if (!file.exists())
            {
                path = FILE;
                file = new File(FILE);
                logger.info("hot update 启动.... load hot config2 ="+path);
            }
            in = new FileInputStream(file);
            properties.load(in);
            String value = properties.getProperty("hot.load.jar");
            if (value != null && !value.isEmpty())
            {
                hotLoadAgentJar = value;
            }
            value = properties.getProperty("hot.pid.file");
            if (value != null && !value.isEmpty())
            {
                pidFile = value;
            }
            return true;
        } catch (Exception e1) {
            logger.error(path +"配置文件加载出错",e1);
            throw  e1;
        }
        finally {
            if (in != null) {
                try { in.close(); } catch (IOException e) { } }
        }
    }

    public String getHotLoadAgentJar() {
        return hotLoadAgentJar;
    }

    public void setHotLoadAgentJar(String hotLoadAgentJar) {
        this.hotLoadAgentJar = hotLoadAgentJar;
    }

    public String getPidFile() {
        return pidFile;
    }

    public void setPidFile(String pidFile) {
        this.pidFile = pidFile;
    }

    public String getPidFromFile() {
        if (pidFile == null || pidFile.isEmpty()) return null;
        File file = new File(pidFile);
        if (!file.exists()) return null;
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            return bufferedReader.readLine().trim();
        } catch (Exception e) {
            logger.error("",e);
            return null;
        } finally {
            try {
                if (bufferedReader == null ) bufferedReader.close();
            } catch (IOException e) {

            }
        }
    }
}
